package cn.lger.icollege.service;

import cn.lger.icollege.dao.NoticeDao;
import cn.lger.icollege.entity.Notice;
import cn.lger.icollege.entity.Teacher;
import cn.lger.icollege.util.SecurityResourceUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Optional;


@Service(value = "noticeService")
public class NoticeService {

    @Resource
    NoticeDao noticeDao;

    @Transactional
    public  Notice saveNotice(Notice notice, String userDetailsUsername){
        notice.setCreateDate(LocalDateTime.now());
        Teacher teacher = new Teacher();
        teacher.setUsername(userDetailsUsername);
        notice.setTeacher(teacher);
        return  noticeDao.save(notice);
    }

    public Page<Notice> findNotices(Pageable pageable){
        return  noticeDao.findAll(pageable);
    }

    public Notice findById(String id) {
        Optional optional = noticeDao.findById(id);
        return optional.isPresent()? (Notice) optional.get() :null;
    }

    @Transactional
    public  Notice editNotice(Notice notice){

        Optional optional=noticeDao.findById(notice.getId());
        if(optional.isPresent()){
            Notice noticedb= (Notice) optional.get();
            notice.setClassroom(noticedb.getClassroom());
            notice.setTeacher(noticedb.getTeacher());
            notice.setCreateDate(noticedb.getCreateDate());
            return  noticeDao.save(notice);
        }
        return null;
    }

    @Transactional
    public String deleteByIdAndTeacherUsername(String id) {
        String success="不成功";
        try {
            noticeDao.deleteByIdAndTeacherUsername(id,SecurityResourceUtil.getUserDetailsUsername());
            success="成功";
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            return  success;
        }
    }

    public Page<Notice> findAll(Pageable pageable) {
        return noticeDao.findAll(pageable);
    }

    public Page<Notice> findNoticesByClassId(Long classId, Pageable pageable) {
        return  noticeDao.findByClassroom_ClassIdOrderByCreateDateDesc(pageable,classId);
    }
}
